package com.datastructure.test.longestcommonprefix;

public class LongestCommonPrefix {
    public String data = "";
    public static void main(String[] args) {
        String[] data = {"abcc","abcc","abcb"};
        LongestCommonPrefix longestCommonPrefix = new LongestCommonPrefix();
        String s = longestCommonPrefix.longestCommonPrefix(data);
        System.out.println(s);
    }

    public String longestCommonPrefix (String[] strs) {
        // write code here
        if(strs==null||strs.length==0){
            return "";
        }

        int rows = strs.length;
        int cols = strs[0].length();
        //开始扫描
        for(int i=0;i<cols;i++){
            char firstChar = strs[0].charAt(i);
            for(int j=1;j<rows;j++){
                if(strs[j].length()==i || strs[j].charAt(i)!=firstChar){
                    return strs[0].substring(0,i);
                }
            }
        }
        return strs[0];
    }

    private void getLongestCommonPrefix(String str, String str1) {
        for(int i = 0;i<=str.length();i++){
            String substring = str.substring(0, i);
            if(str1.contains(substring)&&substring.length()>data.length()){
                data = substring;
            }
        }
    }

    private void getLongestCommonPrefix1(String str, String str1) {
        String temp1 = data;
        for(int i = 0;i<=str.length();i++){
            String substring = str.substring(0, i);
            if(str1.contains(substring)&&substring.length()<=temp1.length()){
                data = substring;
            }
        }
    }

}
